package com.therandoms.rtgdroid.steps;

import java.util.ArrayList;
import java.util.List;

import org.codepond.wizardroid.WizardStep;
import org.codepond.wizardroid.persistence.ContextVariable;
import org.therandoms.textgen.WordnikOptions;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import com.therandoms.rtgdroid.R;
import com.therandoms.rtgdroid.background.WordnikLoaderAsyncTask;
import com.wordnik.client.model.WordObject;

/**
 * A simple wizard step to display wordnik attributions.
 * 
 * @author logan
 *
 */
public class WordnikWordsStep extends WizardStep {

	/**
	 * Stores the options to load from Wordnik.
	 */
	@ContextVariable
	private ArrayList<WordnikOptions> optionsToLoad;

	/**
	 * The progress dialog
	 */
	private ProgressDialog mProgressDialog = null;

	/**
	 * The view to display words in.
	 */
	WebView wordsView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.step_wordnik_show_words, container,
				false);

		if (isAdded()) {
			WordnikOptions[] optionsArr = new WordnikOptions[optionsToLoad
					.size()];
			optionsArr = optionsToLoad.toArray(optionsArr);
			new WordnikLoaderAsyncTask() {
				@Override
				protected void onPreExecute() {
					// do the loading
					mProgressDialog = new ProgressDialog(getActivity());
					mProgressDialog.setTitle("Please wait");
					mProgressDialog.setIndeterminate(true);
					mProgressDialog.setCancelable(false);
					mProgressDialog.show();
				}

				@Override
				protected void onPostExecute(List<WordObject> result) {
					if (result != null) {
						if (isAdded()) {
							wordsView.loadDataWithBaseURL(null,makeHTML(result),"text/html",null,"about:blank");
						}
						try {
							if (mProgressDialog.isShowing()) {
								mProgressDialog.dismiss();
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}.execute(optionsArr);
		}
		wordsView = (WebView) v.findViewById(R.id.wordsView);
		return v;
	}

	/**
	 * required constructor
	 */
	public WordnikWordsStep() {
	}

	/**
	 * Makes the html required for the attribution.
	 * 
	 * @return
	 */
	private String makeHTML(List<WordObject> result) {
		StringBuilder sb = new StringBuilder();
		sb.append(getResources().getString(R.string.wordnik_words_header));
		sb.append("<p><ul>");
		for (WordObject word : result) {
			sb.append("<li><a href=\"https://www.wordnik.com/words/"
					+ word.getWord() + "\">" + word.getWord() + "</a></li>");
		}
		sb.append("</ul></p>");
		sb.append("</body></html>");
		return sb.toString();
	}

}
